'''
游戏需要窗口化（1600x900），最前面窗口

'''

import pyautogui
import pydirectinput
import time
import keyboard
import pygetwindow #兼容旧代码
import pygetwindow as gw
import ctypes
import win32gui
import win32con
import random
import sys
import io
import ctypes
import os
import fileinput
import subprocess
import progressbar
from PIL import ImageGrab,Image
import utils

#游戏基本信息
game_title = '崩坏：星穹铁道'
file_path = r'D:\miHoYo Launcher\games\Star Rail Game\StarRail.exe'

# 窗口位置，游戏启动后获取
x1 = 0
y1 = 0
xing = 0

# 两文件要相同盘符 order：需要打的材料顺序
pyFile = sys.argv[0]
path = os.path.dirname(pyFile)
print(path)
# orderFile = r"D:\Workspace\Python\mihayou\order.txt"
# tempFile = r"D:\Workspace\Python\mihayou\temp_file.txt"
orderFile = os.path.join(path,"order.txt")
tempFile = os.path.join(path,"temp_file.txt")

#每一轮战斗分配的时间 s （根据自己账号练度调整）
fightTime = 25
fight_time_max = 300

def r():
    random_number = random.uniform(0.7, 0.9)
    time.sleep(random_number)
def rr():
    random_number = random.uniform(1.5, 2.0)
    time.sleep(random_number)
def rrr():
    time.sleep(15)
def sleep(t):
    time.sleep(t)#单位=秒
def click(x,y):
    pydirectinput.click(x+x1, y+y1)#点击
    rr()
def press(m):
    # pydirectinput.press(m)#按键
    pydirectinput.keyDown(m)
    sleep(1)
    pydirectinput.keyUp(m)
    rr()
def getpngfromShot2(png,_threshold=0.8,_show_print=True):
    small = Image.open(f"xing/{png}.png")
    big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
    point = utils.getpngfromShot(small,big,_threshold=_threshold)
    if _show_print:
        print(png,point)
    return point

def make_window_active(window_title):
    try:
        # 获取当前活动窗口的句柄
        foreground_window = win32gui.GetForegroundWindow()

        # 获取目标窗口
        windows = gw.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return False
        
        target_window = windows[0]._hWnd  # 获取第一个匹配窗口的句柄
        
        # 判断目标窗口是否为当前活动窗口
        if foreground_window == target_window:
            print(f"Window '{window_title}' is already the active window.")
            return True
        
        # 将窗口设置为活动窗口
        win32gui.ShowWindow(target_window, win32con.SW_RESTORE)  # 恢复窗口（如果它被最小化）
        win32gui.SetForegroundWindow(target_window)  # 设置为前景窗口
        
        print(f"Window '{window_title}' has been set as the active window.")
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False
def is_window_active(window_title):
    try:
        # 获取当前活动窗口的句柄
        foreground_window = ctypes.windll.user32.GetForegroundWindow()

        # 获取所有窗口
        windows = pygetwindow.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return False

        # 获取目标窗口的句柄
        target_window = windows[0]._hWnd  # 获取第一个匹配窗口的句柄
        
        # 判断目标窗口是否为当前活动窗口
        if foreground_window == target_window:
            print(f"Window '{window_title}' is the active window.")
            return True
        else:
            print(f"Window '{window_title}' is not the active window.")
            return False
    except Exception as e:
        print(f"Error: {e}")
        return False
def move_XY(window_title,new_x,new_y):
    try:
        # 获取窗口对象
        windows = pygetwindow.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return
        
        # 选择第一个匹配的窗口
        window = windows[0]
        hwnd = window._hWnd

        # 获取当前窗口的位置信息
        rect = window._rect
        current_width = rect.width
        current_height = rect.height

        # 使用 ctypes 调用 MoveWindow API 移动窗口
        ctypes.windll.user32.MoveWindow(hwnd, new_x, new_y, current_width, current_height, True)
        print(f"Window '{window_title}' moved to ({new_x}, {new_y}) while keeping its size.")
    except Exception as e:
        print(f"Error: {e}")
def getXY():
    #init
    global game_title
    
    while(True):
        make_window_active(game_title)
        sleep(0.5)
        if is_window_active(game_title):
            sleep(0.5)
            move_XY(game_title,0,0)
            break

    # 获取指定标题的程序窗口对象
    program_window = pygetwindow.getWindowsWithTitle(game_title)[0]
    # 获取窗口左上角的位置
    top_left_position = program_window.topleft
    print(top_left_position)
    global x1,y1,xing;
    x1 = top_left_position.x
    y1 = top_left_position.y
    xing = program_window

# 月卡
def monthlyCard():
    sleep(2)
    click(400,400)
    rr()
    click(400,400)
    rr()
    click(400,400)

# 开局短信
def message():
    sleep(2)
    pydirectinput.keyDown("alt")
    click(211,243) #开局短信
    pydirectinput.keyUp("alt")
    sleep(0.7)
    click(787,293) #第一条短信
    for i in range(50):
        click(800,630)
    click(1045,239) #关闭短信
    click(1045,239) #关闭短信
# 邮箱
def email():
    sleep(2)
    press("esc")
    click(1553,264) #邮箱
    click(352,850) #全部领取
    click(352,850) #全部领取
    press("esc")
    press("esc")
# 无名勋礼
def ceremony():
    sleep(2)
    press("esc")
    # click(1220,560) #无名勋礼
    point = getpngfromShot2("无名勋礼")
    if point != 0 :
        click(point[0],point[1]) #找到 无名勋礼 并点击
    else:
        print("没找到 无名勋礼 图片")
        press("esc")
        return #暂停
    rr()
    click(800,92) #任务
    click(1386,800) #一键领取
    click(1386,800) #一键领取
    click(712,88) #奖励
    click(1200,800) #一键领取
    click(1200,800) #一键领取
    press("esc")
    press("esc")

# 每日委托
def delegation():
    sleep(2)
    press("esc")
    rr()
    small = Image.open("xing/entrust.png")
    big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
    point = utils.getpngfromShot(small,big)
    if point != 0 :
        click(point[0],point[1]) #找到 委托 并点击
        sleep(2) # 打开时会卡一会
        click(383,793) # 一键领取
        click(1000,828) # 再次派遣
        sleep(1)
        press("esc")
        press("esc")
    else:
        print("没找到 每日委托 图片")
        press("esc")

# 打开指南
def guide():
    sleep(2)
    press("esc")
    rr()
    # small = Image.open("xing/guide.png")
    # big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
    # point = utils.getpngfromShot(small,big)
    point = getpngfromShot2("guide")
    if point != 0 :
        click(point[0],point[1]) #找到 指南 并点击
    else:
        print("没找到 指南 图片")
        input() #暂停
    
    # click(1100,650)
    r()
# 领取每日星琼
def daily():
    sleep(2)
    guide()
    for i in range(5):
        click(342,718) #每个活跃度
    click(527,290) #星琼条1
    click(527,290) #空白
    # click(1140,290) #星琼条4
    # click(1140,290) #空白
    # click(1340,290) #星琼条5
    # click(1340,290) #空白
    press("esc")
    press("esc")
def fight(n,t=fightTime):
    press("f")
    for i in range(n-1):
        click(1542,786) #增加次数
    click(1333,848) #挑战
    # 增援
    click(1433,646) #支援
    click(1391,852) #入队
    click(1391,852) #开始挑战

    #攻击出发挑战（升级材料需要）
    sleep(2)
    press("w")
    click(400,400) 
    
    print("t*n="+str(t)+"*"+str(n)+"="+str(t*n))
    #等待战斗
    sleep(t*n)

    click(581,818) #退出关卡
    sleep(5)
#处理 order2.txt 文件
def getOrder2():
    with open('order2.txt','r', encoding='utf-8') as file:
        first_line = file.readline().strip()
        if first_line=="":
            first_line = "遗器-药使之径-1"#默认
        print(first_line)
        material,type,number = first_line.split('-')
        print(material,type,number)
        return material,type,number
def setOrder2(_number):
    with open('order2.txt','r', encoding='utf-8') as file:
        lines = file.readlines()
    if lines:
        material,type,number = lines[0].split('-')
        if _number==0:
            lines[0] = ""
        else:
            lines[0] = f'{material}-{type}-{_number}\n'
    with open('order2.txt','w', encoding='utf-8') as file:
        file.writelines(lines)
# 刷材料
def materials():
    sleep(2)
    file_name = orderFile
    file_size = os.path.getsize(file_name)
    # todo 获取当前体力值
    guide()
    click(500,200) #生存索引
    region = (x1+1233,y1+82,x1+1269,y1+102)
    spImg = ImageGrab.grab(bbox=region)
    sp = utils.getSP(spImg)
    if sp==0 or sp==-1:
        print("sp没有设别到 or 设别错误：",sp)
        input() # 暂停
    

    return 
    if file_size == 0:
        print("order file is null")
        money() #刷金币
    else:
        print("order file has data")
        guide()
        click(500,200) #生存索引
        # 查看order文件
        with open(file_name,"r",encoding="utf-8") as file,\
        open (tempFile,"w",encoding="utf-8") as temp_file:
            line = file.readline()
            print(line,end="")
            name,number = line.split("x")
            num = int(number)
            print(name,number)
            
            #拟造花萼（赤）
            if name=="沉沦黑曜":
                print("沉沦黑曜")
                click(400,550) #拟造花萼（赤）
                pyautogui.moveTo(x1+870,y1+500)
                r()
                for i in range(4):
                    pyautogui.scroll(-100)
                click(1283,760) #传送
                sleep(5) #等待传送
                fight(6)
                pass
            elif name=="永恒之花":
                print("永恒之花")
                click(400,550) #拟造花萼（赤）
                pyautogui.moveTo(x1+870,y1+500)
                r()
                for i in range(24):
                    pyautogui.scroll(-100)
                click(1283,760) #传送
                sleep(5) #等待传送
                fight(6)
                pass
            elif name=="群星乐章":
                print("群星乐章")
                click(400,550) #拟造花萼（赤）
                pyautogui.moveTo(x1+870,y1+500)
                r()
                for i in range(38):
                    pyautogui.scroll(-100)
                click(1283,760) #传送
                sleep(5) #等待传送
                fight(6)
                pass
            elif name=="逐星之矢":
                print("逐星之矢")
                click(400,550) #拟造花萼（赤）
                pyautogui.moveTo(x1+870,y1+500)
                r()
                for i in range(18):
                    pyautogui.scroll(-100)
                click(1283,760) #传送
                sleep(5) #等待传送
                fight(6)
                pass
            #凝滞虚影
            elif name=="苦寒晶壳":
                print("苦寒晶壳")
                click(393,656) #凝滞虚影
                pyautogui.moveTo(x1+870,y1+500)
                r()
                for i in range(35):
                    pyautogui.scroll(-100)
                click(1283,760) #传送
                sleep(5) #等待传送
                fight(1,120)
            elif name=="暴风之眼":
                print("暴风之眼")
                click(393,656) #凝滞虚影
                pyautogui.moveTo(x1+870,y1+500)
                r()
                for i in range(5):
                    pyautogui.scroll(-100)
                click(1283,760) #传送
                sleep(5) #等待传送
                fight(1,120)
            #侵蚀隧洞
            elif name=="梦潜之径":
                print("梦潜之径")
                click(393,755) #侵蚀隧洞
                pyautogui.moveTo(x1+659,y1+500)
                r()
                for i in range(29):
                    pyautogui.scroll(-100)
                click(1283,760) #传送a
                sleep(5) #等待传送
                fight(1,80)
            elif name=="幽冥之径":
                print("幽冥之径")
                click(393,755) #侵蚀隧洞
                pyautogui.moveTo(x1+659,y1+500)
                r()
                for i in range(23):
                    pyautogui.scroll(-100)
                click(1283,760) #传送a
                sleep(5) #等待传送
                fight(1,80)

            # 操作order文件
            if num > 1:
                print("not one")
                new_text = name+"x"+str(num-1)+"\n"
                print(new_text)
            else:
                print("only one")
                new_text = ""
                pass
            temp_file.write(new_text)
            temp_file.writelines(file.readlines())
        os.replace(tempFile,file_name)
    pass
def materials2():
    sleep(2)
    global fight_time_max

    guide()
    point = getpngfromShot2("生存索引")
    if point == 0 :
        point = getpngfromShot2("生存索引2")#兼容
    if point != 0 :
        click(point[0],point[1])
        pyautogui.moveTo(x1+455,y1+507) 
        for i in range(6):
            pyautogui.scroll(-100)
        #查看sp
        # sp_region = (x1+1233,y1+81,x1+1269,y1+102)
        sp_region = (x1+1236,y1+81,x1+1269,y1+102)
        sp_img = ImageGrab.grab(bbox=sp_region)
        sp = utils.getSP(sp_img)
        print(f"sp={sp}")
        if sp==0 or sp==-1:
            print("体力识别异常或为0")
            return -1
        #获取要打的材料
        material,type,number = getOrder2()
        #计算sp
        if (sp<30 and material=="周本材料") or \
            (sp<30 and material=="角色晋阶材料") or \
            (sp<40 and material=="遗器") or \
            (sp<10 and material=="行迹材料") :
            print(f"体力不够打 {material}")
            press("esc")
            press("esc")
            return -1
        #周本材料-蛀星的旧靥-2
        # todo、、、、、、、判断material、、、、、、、、、、
        if material=="周本材料":
            point2 = getpngfromShot2(material)
            if point2 != 0 :
                click(point2[0],point2[1])
                pyautogui.moveTo(x1+672,y1+485) 
                for i in range(5):
                    pyautogui.scroll(-100)
                max_wheel = 0
                while max_wheel<6:
                    point3 = getpngfromShot2(type)
                    if point3 != 0 :
                        click(point3[0]+536,point3[1]+60) #传送 1283,584 747, 483
                        #等待传送
                        bar = progressbar.ProgressBar(maxval=60, widgets=[
                            progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
                        ])
                        bar.start()
                        for i in range(60):
                            sleep(1) #等待传送
                            bar.update(i)
                            point4 = getpngfromShot2("挑战")
                            if point4 != 0 :
                                click(point4[0],point4[1])# 挑战
                                click(480,90)# 选第一个队伍
                                click(1439,646)# 支援
                                click(263,492)# 霍霍
                                click(1459,859)# 入队
                                click(1459,859)# 开始挑战
                                break
                        bar.finish()
                        #等待战斗
                        bar = progressbar.ProgressBar(maxval=fight_time_max, widgets=[
                            progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
                        ])
                        bar.start()
                        for i in range(fight_time_max):
                            sleep(1) #等待战斗
                            bar.update(i)
                            point5 = getpngfromShot2("挑战成功",_show_print=False)
                            if point5 != 0 :
                                click(595,820)# 退出关卡
                                n = int(number)
                                setOrder2(n-1)
                                break
                            point6 = getpngfromShot2("挑战失败",_show_print=False)
                            if point6 != 0 :
                                print("挑战失败！！！")
                                click(595,820)# 退出关卡
                                break
                        bar.finish()
                        break
                    else:
                        max_wheel += 1
                        pyautogui.moveTo(x1+672,y1+485) 
                        for i in range(18):
                            pyautogui.scroll(-100)
            else:
                print(f"没找到 {material} 图片")
                press("esc")
                press("esc")
        elif material=="角色晋阶材料":
            point2 = getpngfromShot2(material)
            if point2 != 0 :
                click(point2[0],point2[1])
                max_wheel = 0
                while max_wheel<7:
                    point3 = getpngfromShot2(type)
                    if point3 != 0 :
                        click(point3[0]+536,point3[1]-10) #传送 1283,584 747, 483
                        #等待传送
                        bar = progressbar.ProgressBar(maxval=60, widgets=[
                            progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
                        ])
                        bar.start()
                        for i in range(60):
                            sleep(1) #等待传送
                            bar.update(i)
                            point4 = getpngfromShot2("挑战")
                            if point4 != 0 :
                                click(point4[0],point4[1])# 挑战
                                click(480,90)# 选第一个队伍
                                click(1439,646)# 支援
                                click(263,492)# 霍霍
                                click(1459,859)# 入队
                                click(1459,859)# 开始挑战
                                #向前走两步攻击它
                                press("w")
                                click(500,500)# 攻击它
                                break
                        bar.finish()
                        #等待战斗
                        bar = progressbar.ProgressBar(maxval=fight_time_max, widgets=[
                            progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
                        ])
                        bar.start()
                        for i in range(fight_time_max):
                            sleep(1) #等待战斗
                            bar.update(i)
                            point5 = getpngfromShot2("挑战成功",_show_print=False)
                            if point5 != 0 :
                                click(595,820)# 退出关卡
                                n = int(number)
                                setOrder2(n-1)
                                break
                            point6 = getpngfromShot2("挑战失败",_show_print=False)
                            if point6 != 0 :
                                print("挑战失败！！！")
                                click(595,820)# 退出关卡
                                break
                        bar.finish()
                        break
                    else:
                        max_wheel += 1
                        pyautogui.moveTo(x1+672,y1+485) 
                        for i in range(14):
                            pyautogui.scroll(-100)
            else:
                print(f"没找到 {material} 图片")
                press("esc")
                press("esc")
        elif material=="行迹材料":
            point2 = getpngfromShot2(material)
            if point2 != 0 :
                click(point2[0],point2[1])
                max_wheel = 0
                pyautogui.moveTo(x1+672,y1+485) 
                for i in range(2):
                    pyautogui.scroll(-100)
                while max_wheel<6:
                    point3 = getpngfromShot2(type)
                    if point3 != 0 :
                        click(point3[0]+536,point3[1]-10) #传送 1283,584 747, 483
                        #等待传送
                        bar = progressbar.ProgressBar(maxval=60, widgets=[
                            progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
                        ])
                        bar.start()
                        #计算sp/打怪次数###########
                        sp_n = int(sp/10)
                        if sp_n>6: sp_n=6
                        n = int(number)
                        if n<=6: sp_n = n
                        #
                        for i in range(60):
                            sleep(1) #等待传送
                            bar.update(i)
                            point4 = getpngfromShot2("挑战")
                            if point4 != 0 :
                                for j in range(1,sp_n):
                                    click(1545,786)# 添加打怪次数
                                #
                                click(point4[0],point4[1])# 挑战
                                click(580,90)# 选第二个队伍
                                click(1439,646)# 支援
                                click(263,492)# 霍霍
                                click(1459,859)# 入队
                                click(1459,859)# 开始挑战
                                break
                        bar.finish()
                        #等待战斗
                        bar = progressbar.ProgressBar(maxval=fight_time_max, widgets=[
                            progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
                        ])
                        bar.start()
                        for i in range(fight_time_max):
                            sleep(1) #等待战斗
                            bar.update(i)
                            point5 = getpngfromShot2("挑战成功",_show_print=False)
                            if point5 != 0 :
                                click(595,820)# 退出关卡
                                # n = int(number)
                                setOrder2(int(number)-sp_n)
                                break
                            point6 = getpngfromShot2("挑战失败",_show_print=False)
                            if point6 != 0 :
                                print("挑战失败！！！")
                                click(595,820)# 退出关卡
                                break
                        bar.finish()
                        break
                    else:
                        max_wheel += 1
                        pyautogui.moveTo(x1+672,y1+485) 
                        for i in range(20):
                            pyautogui.scroll(-100)
            else:
                print(f"没找到 {material} 图片")
                press("esc")
                press("esc")
        elif material=="遗器":
            point2 = getpngfromShot2(material)
            if point2 != 0 :
                click(point2[0],point2[1])
                max_wheel = 0
                while max_wheel<6:
                    point3 = getpngfromShot2(type)
                    if point3 != 0 :
                        click(point3[0]+536,point3[1]-10) #传送 1283,584 747, 483
                        #等待传送
                        bar = progressbar.ProgressBar(maxval=60, widgets=[
                            progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
                        ])
                        bar.start()
                        for i in range(60):
                            sleep(1) #等待传送
                            bar.update(i)
                            point4 = getpngfromShot2("挑战")
                            if point4 != 0 :
                                click(point4[0],point4[1])# 挑战
                                click(480,90)# 选第一个队伍
                                click(1439,646)# 支援
                                click(263,492)# 霍霍
                                click(1459,859)# 入队
                                click(1459,859)# 开始挑战
                                break
                        bar.finish()
                        #等待战斗
                        bar = progressbar.ProgressBar(maxval=fight_time_max, widgets=[
                            progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
                        ])
                        bar.start()
                        for i in range(fight_time_max):
                            sleep(1) #等待战斗
                            bar.update(i)
                            point5 = getpngfromShot2("挑战成功",_show_print=False)
                            if point5 != 0 :
                                click(595,820)# 退出关卡
                                n = int(number)
                                setOrder2(n-1)
                                break
                            point6 = getpngfromShot2("挑战失败",_show_print=False)
                            if point6 != 0 :
                                print("挑战失败！！！")
                                click(595,820)# 退出关卡
                                break
                        bar.finish()
                        break
                    else:
                        max_wheel += 1
                        pyautogui.moveTo(x1+672,y1+485) 
                        for i in range(18):
                            pyautogui.scroll(-100)
            else:
                print(f"没找到 {material} 图片")
                press("esc")
                press("esc")
        return 1
    else:
        print("没找到 生存索引 图片")
        press("esc")
        press("esc")

# 刷 金币
def money():
    # guide()
    click(486,207) #生存索引
    click(376,433) #拟造花萼（金）
    click(660,311) #雅利洛-VI
    click(1267,778) #传送
    sleep(20)

    fight(1)
# 刷遗器
def legacy():
    guide()
    click(486,207) #生存索引
    click(408,745) #侵蚀隧洞
    # TODO

def launch_game():
    sleep(2)
    global file_path
    #C:\Program Files\Star Rail\Game\StarRail.exe
    game_name = os.path.basename(file_path)
    call = 'TASKLIST','/FI',f'imagename eq {game_name}'
    output = subprocess.check_output(call).decode('cp1252')
    if game_name in output:
        isLaunchGame = True
    else:
        isLaunchGame = False
    
    #isLaunchGame = True
    if not isLaunchGame:
        print("not running")
        try:
            # 调用subprocess模块来启动.exe文件
            # subprocess.Popen(file_path,creationflags=subprocess.CREATE_NEW_CONSOLE)
            game_process = subprocess.Popen(['start', '', file_path], shell=True)
            result = 1
        except FileNotFoundError as e:
            print("未能找到指定的.exe文件")
            result = 0
        except Exception as e:
            print("发生错误：", str(e))
            result = 0
            
        if(result == 0):
            print("脚本结束...")
            exit()
        else:
            print("等待游戏启动...")
            bar = progressbar.ProgressBar(maxval=60, widgets=[
                progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
            ])
            bar.start()

            #启动程序到加载窗口出来
            for i in range(60):
                #print(str(i)+"-",end="")
                sleep(1) #等待游戏启动
                bar.update(i)
                if any(game_title in win.title for win in pygetwindow.getWindowsWithTitle(game_title)):
                    break
            # bar.finish()

            #初始化位置，将程序放到左上角
            getXY()

            #窗口加载开机动画，等待 点击进入 按钮
            for i in range(60):
                sleep(1) #等待游戏启动
                bar.update(i)

                # 遇到更新的情况
                loc = getpngfromShot2("更新成功2")#确认按钮
                if loc!=0:
                    click(loc[0],loc[1])

                #正常情况
                small = Image.open("xing/点击进入.png")
                big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
                loc = utils.getpngfromShot(small,big)
                loc_has = False
                if(loc!=0): 
                    loc_has = True
                    break
            #点击 第一页 进入游戏 页面
            if loc_has:
                click(loc[0],loc[1]) 
            else:
                click(700,700)
            # sleep(20)

            #从 进入游戏 页面到 完全进入游戏中
            for i in range(60):
                sleep(1) #等待游戏启动
                bar.update(i)
                small = Image.open("xing/加速键.png")
                big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
                loc = utils.getpngfromShot(small,big)
                if(loc!=0): 
                    break
                else:
                    loc2 = getpngfromShot2("点击领取今日补给",_show_print=False)
                    if loc2!=0:
                        print("月卡。。。")
                        monthlyCard()
                        break
            bar.finish()
            print("游戏加载完毕。。。")
            
    else:
        print("running")
        getXY()

def close_game():
    global file_path
    #C:\Program Files\Star Rail\Game\StarRail.exe
    game_name = os.path.basename(file_path)
    try:
        # 使用 taskkill 命令来结束指定进程
        subprocess.run(['taskkill', '/F', '/IM', game_name], check=True)
        print(f"Successfully closed {game_name}")
    except subprocess.CalledProcessError as e:
        print(f"Error: {e}") 
    


# play game
def play():
    print("启动游戏。。。")
    launch_game()    

    # print("月卡。。。")
    # monthlyCard()

    print("每日委托。。。")
    delegation() #每日委托
    
    print("打材料。。。")
    while True:
        res = materials2()#打材料
        if res==-1:break

    print("每日奖励。。。")
    daily() #每日奖励

    # print("开局短信。。。")#没有新角色就么有了
    # message() #开局短信

    print("邮箱。。。")
    email() #邮箱

    print("无名勋礼。。。")
    ceremony() #无名勋礼

    print("auto end...")

    # 是否退出
    if len(sys.argv) > 1:
        print("sys.argv[1] 1111 "+sys.argv[1])
    else:
        print("sys.argv[1] 0000")

# main
if __name__ == "__main__":

    admin = ctypes.windll.shell32.IsUserAnAdmin()
    print("admin=="+str(admin))

    if admin:
        print("have admin")
        # 主程序写在这里
        try:
            play()
        except Exception as e:
            print(e)

        # input() # 防止退出
    else:
        print("not admin")
        # 以管理员权限重新运行程序
        if len(sys.argv) > 1:
            ctypes.windll.shell32.ShellExecuteW(None,"runas", sys.executable, __file__+" "+sys.argv[1], None, 3)
        else:
            ctypes.windll.shell32.ShellExecuteW(None,"runas", sys.executable, __file__, None, 3)

# temp test
if __name__ == "__main__t":
    print("启动游戏。。。")
    launch_game()
    # print("月卡。。。")
    # monthlyCard()
    # print("每日委托。。。")
    # delegation() #每日委托
    # print("打材料-order。。。")
    # while True:
    #     res = materials2()#打材料
    #     if res==-1:break
    
    # getOrder2()
    # setOrder2(2)
    # sleep(2)
    # press("w")
    # ceremony()
